//
//  TJSQLManager.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/25.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import FMDB

class TJSQLManager: NSObject {

    // 创建单例.
    static let shareManager:TJSQLManager = TJSQLManager()
    let dbQueue:FMDatabaseQueue
    
    // 初始化单例的同时,创建数据库表格.
    private override init() {
        // 创建dbqueue对象.
        let dbPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/sinaWeibo.db")
        dbQueue = FMDatabaseQueue(path: dbPath)
        super.init()
        // 创建表格.
        createTable()
    }
    
    private func createTable(){
        
        // 读取资源文件中的sql语句.
        let path = NSBundle.mainBundle().pathForResource("tables.sql", ofType: nil)
        let sql = try! NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
        // 执行sql语句,创建表格.
        dbQueue.inTransaction { (db, rollBack) -> Void in
            do{
            
                try db.executeUpdate(sql as String, values: [])
                TJPrint("执行sql语句成功")
            }catch let error as NSError {
            
                TJPrint("执行sql语句失败:\(error)")
            }
        }
    }
}
